package com.team.mp.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.team.mp.api.bo.SysUserAddBo;
import com.team.mp.api.bo.SysUserBo;
import com.team.mp.constants.RedisKey;
import com.team.mp.mapper.dao.SysUserDao;
import com.team.mp.mapper.dao.SysUserRoleDao;
import com.team.mp.mapper.entity.SysUser;
import com.team.mp.mapper.entity.SysUserRole;
import com.team.mp.api.security.entity.LoginUser;
import com.team.mp.api.service.intf.SysUserService;
import com.team.mp.api.util.JwtUtil;
import com.team.mp.vo.R;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * ━━━━━━Feri出没━━━━━━
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　 ┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　  ┃
 * 　　┃　　　　　　 ┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃    邢哥的代码，怎么会，有bug呢，不可能！
 * 　　　　┃　　　┃
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━永无BUG!━━━━━━
 *
 * @Description:
 * @Author：邢朋辉
 * @Date: 2023/3/25 16:13
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Resource
    private SysUserDao dao;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private StringRedisTemplate template;
    @Resource
    private SysUserRoleDao userRoleDao;

    @Override
    public R add(SysUserAddBo bo) {
        //1.验证
        if(bo!=null){
            //2组装对象
            SysUser user=new SysUser();
            user.setUsername(bo.getUsername());
            //密码转为密文
            user.setPassword(passwordEncoder.encode(bo.getPassword()));
            //3.操作数据库
            if(dao.insert(user)>0){
                //4.新增用户对应的角色
                userRoleDao.insert(new SysUserRole(user.getId(),bo.getRid()));

                return R.ok();
            }
        }
        return R.fail();
    }

    @Override
    public R login(SysUserBo bo) {
        //1.从Spring Security 获取UserDetails--->SysUser
        UsernamePasswordAuthenticationToken token1 =
                new UsernamePasswordAuthenticationToken(bo.getUsername(),bo.getPassword());
        Authentication authentication=authenticationManager.authenticate(token1);
        //2.验证Spring Security 的认证是否成功
        if(!Objects.isNull(authentication)){
            //3.获取当前的登录用户
            LoginUser loginUser= (LoginUser) authentication.getPrincipal();
            SysUser user=loginUser.getUser();
            //4.成功，生成令牌 JWT形式
            String token= JwtUtil.createJwt(user.getId()+"");
            //5.存储到Redis String类型
            template.opsForValue().set(RedisKey.AUTH_TOKEN +user.getId(), JSON.toJSONString(loginUser));

            //5.返回令牌
            return R.ok(token);
        }
        return R.fail("亲，登录失败，请检查！");
    }

    @Override
    public R logout() {
        //1.获取当前的认证信息
        UsernamePasswordAuthenticationToken authentication
                = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

            LoginUser loginUser= (LoginUser) authentication.getPrincipal();
            //2.删除Redis的令牌
            template.delete(RedisKey.AUTH_TOKEN+loginUser.getUser().getId());
            return R.ok();
    }

    @Override
    public R queryPage(int page, int size) {
        QueryWrapper<SysUser> wrapper=new QueryWrapper<>();
        wrapper.orderByAsc("id");
        return R.ok(dao.selectPage(new Page<>(page,size),wrapper));
    }

    @Override
    public R updatePass(String pass) {
        UsernamePasswordAuthenticationToken authentication
                = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser= (LoginUser) authentication.getPrincipal();
        SysUser user=new SysUser();
        user.setId(loginUser.getUser().getId());
        user.setPassword(passwordEncoder.encode(pass));
        if(dao.updateById(user)>0){
            template.delete("rbac:sysuser:token:"+loginUser.getUser().getId());
            return R.ok();
        }else {
            return R.fail();
        }
    }
}
